package main.java.FSMDE.persistence;

import java.util.ArrayList;
import java.util.Iterator;

import main.java.ERMDE.models.Diagram;
import main.java.FSMDE.models.ComplexComponent;
import main.java.FSMDE.models.Component;
import main.java.FSMDE.models.ComponentCollection;
import main.java.FSMDE.persistence.ComponentCollectionXmlManager;

import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class ComponentCollectionXmlManager {

	private ArrayList<Diagram> ermDiagrams;

	public ComponentCollectionXmlManager(ArrayList<Diagram> ermDiagrams) {
		this.ermDiagrams = ermDiagrams;
	}

	public ComponentCollection getItemFromXmlElement(Element componentsElem)
			throws NumberFormatException, Exception {

		ComponentCollection compCollection = new ComponentCollection();
		if (componentsElem == null)
			return compCollection;
		for (int i = 0; i < componentsElem.getElementsByTagName("component")
				.getLength(); i++) {
			Element component = (Element) componentsElem.getElementsByTagName(
					"component").item(i);
			ComponentXmlManager componentXmlManager = new ComponentXmlManager();
			componentXmlManager.setErmDiagrams(ermDiagrams);
			Component c = componentXmlManager.getItemFromElement(component);
			if (componentNotAdded(c, compCollection)) {
				compCollection.add(c);
			}
		}
		return compCollection;
	}

	private boolean componentNotAdded(Component c,
			ComponentCollection compCollection) {

		for (Component aux : compCollection) {
			if (c.getId().toString().equals(aux.getId().toString())) {
				return false;
			}
			if (aux instanceof ComplexComponent) {
				if (componentNotAdded(c,
						((ComplexComponent) aux).getComponents()) == false) {
					return false;
				}
			}
		}
		return true;
	}

	public Element getElementFromItem(ComponentCollection compCol, Document doc) {
		Element compColElement = doc.createElement("components");

		Iterator<Component> ite = compCol.iterator();

		while (ite.hasNext()) {
			Component comp = ite.next();
			compColElement.appendChild(new ComponentXmlManager()
					.getElementFromItem(comp, doc));
		}
		return compColElement;
	}
}
